package com.java.advance.rpc.client.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by aivin on 2019/3/28.
 */
public class Server {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket();
            serverSocket.bind(new InetSocketAddress(10001));
            System.out.println("Server is running......");
            while (true) {
                new Thread(new ServerTask(serverSocket.accept())).start();
            }

        } finally {
            serverSocket.close();
        }
    }

    private static class ServerTask implements Runnable {

        private Socket socket = null;

        public ServerTask(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {

            try (
                    ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
                    ObjectInputStream intput = new ObjectInputStream(socket.getInputStream());
            ) {
                String userName = intput.readUTF();
                System.out.println("accept msg :" + userName);
                output.writeUTF("Hello:" + userName);
                output.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }
    }
}
